import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

const List<String> defaultImages = [
  "https://ww3.sinaimg.cn/large/006y8mN6ly1g6e2tdgve1j30ku0bsn75.jpg",
  "https://ww3.sinaimg.cn/large/006y8mN6ly1g6e2whp87sj30ku0bstec.jpg",
  "https://ww3.sinaimg.cn/large/006y8mN6ly1g6e2tl1v3bj30ku0bs77z.jpg",
];

var imageWidth = 750.0;
var imageHeight = 424.0;
var imageWidthHeightRatio = imageWidth / imageHeight;

class CommonImagePicker extends StatefulWidget {
  final ValueChanged<List<File>>? onChanged;

  const CommonImagePicker({
    Key? key,
    this.onChanged,
  }) : super(key: key);

  @override
  _CommonImagePickerState createState() => _CommonImagePickerState();
}

class _CommonImagePickerState extends State<CommonImagePicker> {
  final _picker = ImagePicker();
  List<File> _files = [];

  _getImage() async {
    await showModalBottomSheet(
      context: context,
      builder: (context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                title: Text("拍照"),
                leading: Icon(Icons.camera_alt),
                onTap: _camera,
              ),
              Divider(height: 1),
              ListTile(
                title: Text("相册"),
                leading: Icon(Icons.photo_album),
                onTap: _photo,
              ),
              Divider(height: 1),
              ListTile(
                title: Text("取消"),
                leading: Icon(Icons.cancel),
                onTap: () => Navigator.of(context).pop(),
              ),
            ],
          ),
        );
      },
    );
  }

  _camera() async {
    Navigator.of(context).pop();
    final pickedFile = await _picker.pickImage(source: ImageSource.camera);
    _dealImage(pickedFile);
  }

  _photo() async {
    Navigator.of(context).pop();
    final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
    _dealImage(pickedFile);
  }

  _dealImage(XFile? pickedFile) async {
    if (pickedFile != null) {
      final file = File(pickedFile.path);
      setState(() {
        _files.add(file);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    double width = (MediaQuery.of(context).size.width - 10.0 * 4) / 3;
    double height = width / imageWidthHeightRatio;

    Widget addButton = GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: _getImage,
      child: Container(
        width: width,
        height: height,
        decoration: BoxDecoration(color: Colors.grey),
        child: Center(
          child: Text(
            "+",
            style: TextStyle(
              fontSize: 40.0,
              fontWeight: FontWeight.w100,
            ),
          ),
        ),
      ),
    );

    Widget wrapper(File file) {
      return Container(
        width: width,
        height: height,
        child: Stack(
          children: [
            Image.file(
              file,
              width: width,
              height: height,
              fit: BoxFit.cover,
            ),
            GestureDetector(
              onTap: () => setState(() => _files.remove(file)),
              behavior: HitTestBehavior.translucent,
              child: Align(
                alignment: Alignment.topRight,
                child: Icon(
                  Icons.delete_forever,
                  color: Colors.red,
                ),
              ),
            ),
          ],
        ),
      );
    }

    List<Widget> list = _files.map((e) => wrapper(e)).toList()..add(addButton);

    return Container(
      padding: EdgeInsets.all(10.0),
      child: Wrap(
        spacing: 10.0,
        runSpacing: 10.0,
        children: list,
      ),
    );
  }
}
